package csu.web.credit_bank.controller;

import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.request.AlipayUserInfoShareRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.alipay.api.response.AlipayUserInfoShareResponse;
import csu.web.credit_bank.service.UsersService;
import csu.web.credit_bank.utils.Result;
import csu.web.credit_bank.utils.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;

@RestController
@RequestMapping("/api/alipay")
public class AlipayController {

    @Autowired
    private AlipayClient alipayClient;

    @Value("${alipay.app-id}")
    private String appId;
    @Autowired
    private UsersService usersService;

    private final String frontendUrl = "http://localhost:3000";



    @GetMapping("/callback")
    public void alipayCallback(@RequestParam("auth_code") String authCode, HttpServletResponse httpResponse) throws IOException {
        String token = null;
        try {
            AlipaySystemOauthTokenRequest tokenRequest = new AlipaySystemOauthTokenRequest();
            tokenRequest.setGrantType("authorization_code");
            tokenRequest.setCode(authCode);
            AlipaySystemOauthTokenResponse tokenResponse = alipayClient.execute(tokenRequest);
            if (!tokenResponse.isSuccess()) throw new RuntimeException("Failed to exchange token");
            String accessToken = tokenResponse.getAccessToken();
            AlipayUserInfoShareRequest userInfoRequest = new AlipayUserInfoShareRequest();
            AlipayUserInfoShareResponse userInfoResponse = alipayClient.execute(userInfoRequest, accessToken);
            if (!userInfoResponse.isSuccess()) throw new RuntimeException("Failed to get user info");

            Result result = usersService.loginOrRegisterByAlipay(
                    userInfoResponse.getEmail(),       // 使用邮箱
                    userInfoResponse.getNickName(),    // 使用昵称
                    userInfoResponse.getAvatar()       // 使用头像
            );

            if (result.getCode() == StatusCode.SUCCESS.getCode()) {
                Map<String, Object> data = (Map<String, Object>) result.getData();
                token = (String) data.get("token");
            } else {
                throw new RuntimeException(result.getMsg());
            }
        } catch (Exception e) {
            e.printStackTrace();
            String errorMessage = URLEncoder.encode(e.getMessage(), StandardCharsets.UTF_8);
            httpResponse.sendRedirect(frontendUrl + "/login/error?msg=" + errorMessage);
            return;
        }
        httpResponse.sendRedirect(frontendUrl + "/login/callback?token=" + token);
    }
}